import pymysql
from dbutils.pooled_db import PooledDB
import time
import threading
from datetime import datetime
from config import *



lock = threading.Lock()

class MySQLConnectionPool:

    def __init__(self,):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            mincached=0,  # 初始化时，链接池中至少创建的链接，0表示不创建
            maxconnections=0,  # 连接池允许的最大连接数，0和None表示不限制连接数
            blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
            host=host,
            port=port,
            user=user,
            password=password,
            database=database
        )

    def open(self):
        self.conn = self.pool.connection()
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)  # 表示读取的数据为字典类型
        return self.conn, self.cursor

    def close(self, cursor, conn):
        # print('关闭')
        cursor.close()
        conn.close()

    def select_one(self, sql, *args):
        """查询单条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def select_all(self, sql, args):
        """查询多条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def insert_one(self, sql, args):
        """插入单条数据"""
        self.execute(sql, args, isNeed=True)

    def camel_to_underline(self,s):
        result = ""
        for char in s:
            if char.isupper():
                result += '_' + char.lower()
            else:
                result += char
        return result[1:] if result.startswith('_') else result

    def save_to_mysql(self,data_dict, table_name):
        print(data_dict)
        # 连接到 MySQL 数据库
        conn, cursor = self.open()
        data_dict_keys = data_dict.keys()
        # 构建插入语句
        columns = ', '.join(list(data_dict_keys))
        values = ', '.join(['%s' for _ in data_dict.values()])
        sql = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"

        # 执行插入操作
        try:
            cursor.execute(sql, tuple(data_dict.values()))
            conn.commit()
        except Exception as e:
            print(e)
            conn.rollback()
        self.close(conn, cursor)


    def insert_all(self, sql, datas):
        for i in range(5):
            lock.acquire()
            """插入多条批量插入"""
            conn, cursor = self.open()
            try:
                self.conn.ping(reconnect=True)
                cursor.executemany(sql, datas)
                conn.commit()
                print('mysql存储成功！！！')
                lock.release()
                return {'result': True, 'id': int(cursor.lastrowid)}
            except Exception as err:
                # time.sleep(3)
                print('连接mysql出错',err)
                conn.rollback()
                continue
            finally:
                self.close(self.cursor, self.conn)

    def update_one(self, sql, args):
        """更新数据"""
        self.execute(sql, args, isNeed=True)

    def delete_one(self, sql, *args):
        """删除数据"""
        self.execute(sql, args, isNeed=True)

    def execute(self, sql, args, isNeed=False):
        """
        执行
        :param isNeed 是否需要回滚
        """
        conn, cursor = self.open()
        if isNeed:
            try:
                cursor.execute(sql, args)
                conn.commit()
            except:
                conn.rollback()
        else:
            cursor.execute(sql, args)
            conn.commit()
        self.close(conn, cursor)